from flask import Blueprint, request, jsonify, current_app
import logging, os, json
from utils import common
import datetime

ai_bp = Blueprint('ai', __name__, url_prefix='/ai')


@ai_bp.route('/info/get', methods=['GET'])
def get():
    params = dict(request.args)
    data = current_app.config['DB'].get_info(params)
    return jsonify({'code':0, 'data':data})


@ai_bp.route('/info/create', methods=['POST'])
def create():
    params = request.json
    # params['date'] = datetime.datetime.fromisoformat(params['date'][:-1])
    params['date'] = datetime.datetime.strptime(params['date'], '%Y-%m-%d')
    params['tags'] = json.dumps(params['tags'], ensure_ascii=False)

    if not params.get('id'):
        res = current_app.config['DB'].insert_info(params)
    else:
        res = current_app.config['DB'].update_info(params)
    if res:
        return jsonify({'code':0})
    else:
        return jsonify({'code':400})

# @ai_bp.route('/info/update', methods=['POST'])
# def update():
#     params = request.json
#     # params['date'] = datetime.datetime.fromisoformat(params['date'][:-1])
#     params['date'] = datetime.datetime.strptime(params['date'], '%Y-%m-%d')
#     res = current_app.config['DB'].update_info(params)
#     if res:
#         return jsonify({'code':0})
#     else:
#         return jsonify({'code':400})

@ai_bp.route('/info/remove', methods=['GET'])
def delete():
    params = dict(request.args)
    
    res = current_app.config['DB'].delete_info(params)
    if res:
        return jsonify({'code':0})
    else:
        return jsonify({'code':400})


@ai_bp.route('/tags/get', methods=['GET'])
def get_tags():
    data = ['开源', '机器人']
   
    return jsonify({'code':0, 'data':data})

@ai_bp.record
def log(app):
    logging.info('register ai blueprint')
